package com.javasea.nio.checksum;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *@ClassName CheckSumUtil
 *@Description TODO
 *@Author longxiaonan@163.com
 *@Date 2021/1/24 0024 22:49
 */
public class CheckSumUtil {

    public static boolean checkSum(Object obj, int checkSum) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = objectMapper.writeValueAsBytes(obj);
//        String s = "abcdefg1111134234232423";
        byte sum  = 0;
        for (int i = 0, len = bytes.length; i < len; i++){
            sum += bytes[i];
        }
        // 求和
        System.out.println(sum);
        // 接收方校验
        int a = sum + checkSum + 1;
        System.out.println("最后的校验值为：" + sum);
        return a == 0;
    }

    public static int getCheckSum(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = objectMapper.writeValueAsBytes(obj);
        byte sum  = 0;
        for (int i = 0, len = bytes.length; i < len; i++){
            sum += bytes[i];
        }
        // 求和
        System.out.println("求和的值为：" + sum);
        // 取反
        int ss = ~sum;
        System.out.println("取反的值为：" + ss);
        return ss;
    }

}
